package com.mo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.mo.common.Result;
import com.mo.entity.Menu;
import com.mo.entity.RoleMenu;
import com.mo.entity.params.RoleMenuParam;
import com.mo.service.RoleMenuService;
import com.mo.utils.MenuTreeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class RoleMenuController {
    @Resource
    private RoleMenuService roleMenuService;

    @GetMapping("role-menu")
    public Result getMenuByRoleId(int roleId) {
        List<Menu> menus = roleMenuService.getMenuByRoleId(roleId);
        List<Menu> menuTree = MenuTreeUtil.builderMenuTree2(menus, 0);
        return Result.success(menuTree);
    }

    @Transactional
    @PostMapping("role-menu")
    @PreAuthorize("hasAuthority('sys:system:role:update')")
    public Result saveRoleMenu(@RequestBody RoleMenuParam roleMenuParam) {
        if (Objects.isNull(roleMenuParam.getMenuIdList())) {
            return Result.error();
        }

        // 先删除全部
        LambdaQueryWrapper<RoleMenu> removeWrapper = Wrappers.<RoleMenu>lambdaQuery()
                .eq(RoleMenu::getRoleId, roleMenuParam.getRoleId());
        roleMenuService.remove(removeWrapper);

        if (roleMenuParam.getMenuIdList().isEmpty()) {
            return Result.success();
        }

        // 再添加新的
        ArrayList<RoleMenu> roleMenus = new ArrayList<>();
        for (Integer item : roleMenuParam.getMenuIdList()) {
            RoleMenu roleMenu = new RoleMenu(null, roleMenuParam.getRoleId(), item);
            roleMenus.add(roleMenu);
        }
        boolean save = roleMenuService.saveBatch(roleMenus);
        if (save) {
            return Result.success();
        }
        return Result.error();
    }

    @GetMapping("check-keys")
    public Result getCheckKeys(@RequestParam int roleId) {
        LambdaQueryWrapper<RoleMenu> wrapper = Wrappers.<RoleMenu>lambdaQuery()
                .eq(RoleMenu::getRoleId, roleId);
        List<Integer> checkKeys = Optional.ofNullable(roleMenuService.list(wrapper))
                .orElse(new ArrayList<>())
                .stream()
                .map(RoleMenu::getMenuId)
                .collect(Collectors.toList());
        return Result.success(checkKeys);
    }
}
